<template>
  <div class="message-board-container">
    <div class="header">
      <h2>留言板</h2>
      <el-button type="primary" @click="openAddDialog">发表留言</el-button>
    </div>

    <!-- 留言展示区 -->
    <div class="bubbles-container" ref="bubblesContainer">
      <bubble-canvas ref="bubbleCanvas" :messages="messages" @bubble-click="handleBubbleClick" />
    </div>

    <!-- 留言对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :before-close="handleDialogClose"
    >
      <div v-if="dialogType === 'detail'" class="message-detail">
        <div class="message-author">{{ currentMessage.author }}</div>
        <div class="message-content">{{ currentMessage.content }}</div>
        <div class="message-time">{{ formatTime(currentMessage.createTime) }}</div>
        
        <div class="message-actions">
          <el-button type="primary" @click="openEditDialog(currentMessage)">编辑</el-button>
          <el-button type="danger" @click="confirmDelete(currentMessage)">删除</el-button>
        </div>
      </div>
      
      <el-form v-else :model="messageForm" :rules="rules" ref="messageFormRef" label-width="80px">
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="messageForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入留言内容"
          ></el-input>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button v-if="dialogType === 'add'" type="primary" @click="submitMessage" :loading="submitting">提交</el-button>
          <el-button v-if="dialogType === 'edit'" type="primary" @click="updateMessage" :loading="submitting">更新</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="400px"
    >
      <div>您确定要删除这条留言吗？</div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="deleteMessage" :loading="deleting">删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, onActivated, onDeactivated } from 'vue';
import { ElMessage } from 'element-plus';
import BubbleCanvas from '../components/BubbleCanvas.vue';
import axios from 'axios';

// 状态变量
const messages = ref();
const dialogVisible = ref(false);
const dialogType = ref('add'); // 'add', 'edit' 或 'detail'
const dialogTitle = ref('发表留言');
const currentMessage = ref({});
const submitting = ref(false);
const deleteDialogVisible = ref(false);
const deleting = ref(false);
const bubbleCanvas = ref(null);
const bubblesContainer = ref(null);

// 表单数据和验证规则
const messageForm = reactive({
  content: ''
});

const rules = {
  content: [
    { required: true, message: '请输入留言内容', trigger: 'blur' },
    { min: 1, max: 200, message: '留言内容不能超过200个字符', trigger: 'blur' }
  ]
};

// 表单引用
const messageFormRef = ref(null);

// 提交留言
const submitMessage = async () => {
  try {
    // 表单验证
    if (!messageFormRef.value) {
      ElMessage.error('表单引用错误');
      return;
    }
    await messageFormRef.value.validate();
    
    submitting.value = true;
    
    // 构建请求数据
    const requestData = {
      message: messageForm.content
    };
    
    // 调用后端 API
    const response = await axios.post('/api/message/add', requestData);
    
    if (response.data.code === '200') {
      // 重置表单
      messageForm.content = '';
      
      // 关闭对话框
      dialogVisible.value = false;
      
      // 显示成功消息
      ElMessage.success('留言发表成功');
      
      // 重新获取留言列表
      fetchMessages();
    } else {
      ElMessage.error(response.data.message || '提交留言失败');
    }
    
    submitting.value = false;
  } catch (error) {
    console.error('提交留言失败:', error);
    ElMessage.error('提交留言失败');
    submitting.value = false;
  }
};

// 打开添加留言对话框
const openAddDialog = () => {
  dialogType.value = 'add';
  dialogVisible.value = true;
};

// 处理气泡点击
const handleBubbleClick = (message) => {
  currentMessage.value = message;
  dialogType.value = 'detail';
  dialogTitle.value = '留言详情';
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = (message) => {
  currentMessage.value = message;
  messageForm.content = message.content;
  dialogType.value = 'edit';
  dialogTitle.value = '编辑留言';
  dialogVisible.value = true;
};

// 更新留言
const updateMessage = async () => {
  try {
    // 表单验证
    if (!messageFormRef.value) {
      ElMessage.error('表单引用错误');
      return;
    }
    await messageFormRef.value.validate();
    
    submitting.value = true;
    
    // 构建请求数据
    const requestData = {
      message: messageForm.content
    };
    
    // 调用后端 API - 假设更新接口也是类似的路径格式
    const response = await axios.put(`/api/message/${currentMessage.value.id}/update`, requestData);
    
    if (response.data.code === '200') {
      // 重置表单
      messageForm.content = '';
      
      // 关闭对话框
      dialogVisible.value = false;
      
      // 显示成功消息
      ElMessage.success('留言更新成功');
      
      // 重新获取留言列表
      fetchMessages();
    } else {
      ElMessage.error(response.data.message || '更新留言失败');
    }
    
    submitting.value = false;
  } catch (error) {
    console.error('更新留言失败:', error);
    ElMessage.error('更新留言失败');
    submitting.value = false;
  }
};

// 确认删除留言
const confirmDelete = (message) => {
  currentMessage.value = message;
  deleteDialogVisible.value = true;
};

// 删除留言
const deleteMessage = async () => {
  try {
    deleting.value = true;
    
    // 调用后端 API - 使用DELETE请求
    const response = await axios.delete(`/api/message/${currentMessage.value.id}/delete`);
    
    if (response.data.code === '200') {
      // 关闭对话框
      deleteDialogVisible.value = false;
      dialogVisible.value = false;
      
      // 显示成功消息
      ElMessage.success('留言删除成功');
      
      // 重新获取留言列表
      fetchMessages();
    } else {
      ElMessage.error(response.data.message || '删除留言失败');
    }
    
    deleting.value = false;
  } catch (error) {
    console.error('删除留言失败:', error);
    ElMessage.error('删除留言失败');
    deleting.value = false;
  }
};

// 关闭对话框
const handleDialogClose = () => {
  dialogVisible.value = false;
};

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 获取留言列表
// updateDataOnly: 如果为true，只更新数据而不重新生成气泡
const fetchMessages = async (updateDataOnly = false) => {
  try {
    console.log(`[MessageBoard] 开始获取留言数据${updateDataOnly ? '(仅更新数据)' : ''}`);
    const response = await axios.get('/api/message/list');
    
    // 输出原始响应数据，检查数据结构
    console.log('[MessageBoard] API原始响应:', JSON.stringify(response.data));
    
    if (response.data.code === '200') {
      // 检查data字段是否存在且是数组
      const messageData = response.data.data || [];
      console.log('[MessageBoard] 原始消息数据:', messageData);
      
      // 将后端返回的数据转换为前端需要的格式
      const newMessages = Array.isArray(messageData) ? messageData.map(item => ({
        id: item.id,
        author: `留言${item.id}`, // 后端没有作者字段，使用ID作为替代
        content: item.message,
        createTime: new Date(item.createTime).getTime()
      })) : [];
      
      // 如果只是更新数据，且已经有气泡存在，则保持气泡位置不变，只更新内容
      if (updateDataOnly && bubbleCanvas.value && messages.value.length > 0) {
        // 调用BubbleCanvas组件的更新数据方法
        bubbleCanvas.value.updateBubbleContents(newMessages);
        console.log('[MessageBoard] 只更新气泡内容，保持气泡位置不变');
      } else {
        // 否则完全替换消息数据，会触发气泡重新生成
        messages.value = newMessages;
        console.log('[MessageBoard] 完全替换消息数据，触发气泡重新生成');
      }
      
      console.log('[MessageBoard] 转换后的消息数据:', newMessages);
      console.log('[MessageBoard] 已加载留言数据:', newMessages.length, '条');
      
      // 如果没有数据，添加测试数据
      if (messages.value.length === 0) {
        console.log('[MessageBoard] 没有数据，添加测试数据');
        messages.value = [
          { id: 1, author: '测试用户1', content: '这是一条测试留言，用于测试气泡显示。', createTime: new Date().getTime() },
          { id: 2, author: '测试用户2', content: '考研加油！大家一起努力！', createTime: new Date().getTime() - 43200000 },
          { id: 3, author: '测试用户3', content: '学习使我快乐！', createTime: new Date().getTime() - 86400000 }
        ];
      }
    } else {
      console.error('[MessageBoard] 获取留言数据失败:', response.data.message);
      ElMessage.error('获取留言数据失败');
    }
  } catch (error) {
    console.error('[MessageBoard] 获取留言数据异常:', error);
    ElMessage.error('获取留言数据失败');
    
    // 出错时添加测试数据，确保气泡能显示
    messages.value = [
      { id: 1, author: '测试用户1', content: '这是一条测试留言，用于测试气泡显示。', createTime: new Date().getTime() },
      { id: 2, author: '测试用户2', content: '考研加油！大家一起努力！', createTime: new Date().getTime() - 43200000 },
      { id: 3, author: '测试用户3', content: '学习使我快乐！', createTime: new Date().getTime() - 86400000 }
    ];
  }
};

// 生命周期钩子
// 自动刷新定时器
let autoRefreshTimer = null;
const AUTO_REFRESH_INTERVAL = 10 * 60 * 1000; // 10分钟

// 启动自动刷新定时器
const startAutoRefresh = () => {
  // 清除现有定时器
  if (autoRefreshTimer) {
    clearInterval(autoRefreshTimer);
  }
  
  // 设置新的定时器，每10分钟自动获取数据
  autoRefreshTimer = setInterval(() => {
    console.log('[MessageBoard] 自动刷新数据');
    fetchMessages(true); // 传入true表示只更新数据，不重新生成气泡
  }, AUTO_REFRESH_INTERVAL);
  
  console.log(`[MessageBoard] 启动自动刷新定时器，间隔: ${AUTO_REFRESH_INTERVAL / 1000} 秒`);
};

// 停止自动刷新定时器
const stopAutoRefresh = () => {
  if (autoRefreshTimer) {
    clearInterval(autoRefreshTimer);
    autoRefreshTimer = null;
    console.log('[MessageBoard] 停止自动刷新定时器');
  }
};

onMounted(async () => {
  console.log('[MessageBoard] 组件挂载开始');
  // 先加载数据，等待数据加载完成
  await fetchMessages();
  console.log('[MessageBoard] 数据加载完成，消息数量:', messages.value.length);
  
  // 启动自动刷新定时器
  startAutoRefresh();
  
  console.log('[MessageBoard] 组件挂载完成');
});

// 组件即将被卸载时清理资源
onBeforeUnmount(() => {
  console.log('[MessageBoard] 组件即将卸载，开始清理资源');
  // 停止自动刷新定时器
  stopAutoRefresh();
  
  // 手动清理BubbleCanvas组件资源
  if (bubbleCanvas.value) {
    bubbleCanvas.value.cleanup();
  }
  console.log('[MessageBoard] 资源清理完成');
});

// 组件停用时清理资源
onDeactivated(() => {
  console.log('[MessageBoard] 组件停用，开始清理资源');
  // 手动清理BubbleCanvas组件资源
  try {
    if (bubbleCanvas.value) {
      bubbleCanvas.value.cleanup();
    }
  } catch (error) {
    console.error('[MessageBoard] 清理资源时发生错误:', error);
  }
  console.log('[MessageBoard] 资源清理完成');
});

// 组件激活时重新初始化
onActivated(() => {
  console.log('[MessageBoard] 组件激活，开始重新初始化');
  // 重新初始化BubbleCanvas组件
  // 使用setTimeout确保 DOM 已经完全渲染
  setTimeout(() => {
    try {
      if (bubbleCanvas.value) {
        bubbleCanvas.value.reinitialize();
      }
    } catch (error) {
      console.error('[MessageBoard] 重新初始化时发生错误:', error);
    }
    console.log('[MessageBoard] 重新初始化完成');
  }, 200);
});
</script>

<style scoped>
.message-board-container {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #b8c6db 0%, #f5f7fa 100%);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.bubbles-container {
  flex: 1;
  position: relative;
  overflow: hidden;
}

.message-detail {
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.message-author {
  font-weight: bold;
  font-size: 18px;
  margin-bottom: 10px;
  color: #409eff;
}

.message-content {
  font-size: 16px;
  line-height: 1.6;
  margin-bottom: 15px;
  white-space: pre-wrap;
  word-break: break-word;
}

.message-time {
  font-size: 14px;
  color: #909399;
  text-align: right;
  margin-bottom: 15px;
}

.message-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

.message-toast {
  min-width: 300px;
  padding: 15px 20px;
  border-radius: 8px;
  background: rgba(255, 192, 203, 0.9) !important; /* 粉色透明背景 */
  backdrop-filter: blur(5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

:deep(.message-toast .el-message__content) {
  font-size: 16px;
  color: #333;
  line-height: 1.5;
  word-break: break-word;
  text-align: left;
}

:deep(.message-toast .el-message__closeBtn) {
  color: #333;
}
</style>
